/**
 * index_iterator.cpp
 */
#include <cassert>

#include "storage/index/index_iterator.h"

namespace bustub {

/*
 * NOTE: you can change the destructor/constructor method here
 * set your own input parameters
 */
INDEX_TEMPLATE_ARGUMENTS
INDEXITERATOR_TYPE::IndexIterator() = default;

INDEX_TEMPLATE_ARGUMENTS
INDEXITERATOR_TYPE::IndexIterator(LeafPage* page,BufferPoolManager* bufferpool,int32_t idx){
    this->nowPage = page;
    this->idx = idx;
    this->buffer_pool_manager_ = bufferpool;
}

INDEX_TEMPLATE_ARGUMENTS
INDEXITERATOR_TYPE::~IndexIterator() = default;  // NOLINT

INDEX_TEMPLATE_ARGUMENTS
auto INDEXITERATOR_TYPE::IsEnd() -> bool {
    if(this->idx==this->nowPage->GetSize()&&this->nowPage->GetNextPageId()==-1)
        return true;
    return false;
}

INDEX_TEMPLATE_ARGUMENTS
auto INDEXITERATOR_TYPE::operator*() -> const MappingType & { 
 
    MappingType *mapp = new MappingType(this->nowPage->KeyAt(idx),this->nowPage->ValueAt(idx));
    return *mapp;//MappingType(this->nowPage->KeyAt(idx),this->nowPage->ValueAt(idx));//{this->nowPage->KeyAt(idx),this->nowPage->ValueAt(idx)};
}

INDEX_TEMPLATE_ARGUMENTS
auto INDEXITERATOR_TYPE::operator++() -> INDEXITERATOR_TYPE & { 
    if(this->idx+1<this->nowPage->GetSize()){
        this->idx++;
        return *this;
    }
    else{
        if(this->nowPage->GetNextPageId()!=-1){
            this->nowPage = reinterpret_cast<LeafPage*>(this->buffer_pool_manager_->FetchPage(this->nowPage->GetNextPageId())->GetData());
            this->idx=0;
            return *this;
        }else{
            this->idx++;
            return *this;//比较两个iter是否相同，看page，bufferpool，idx，现在如果是end，则idx为GetSize，但是idx取到n-1就到尾部了
        }                  //判断如果是nextpage =-1 ，即后面没有页面了，且到尾部了，就将idx加1，使得等于end
    }   
}

template class IndexIterator<GenericKey<4>, RID, GenericComparator<4>>;

template class IndexIterator<GenericKey<8>, RID, GenericComparator<8>>;

template class IndexIterator<GenericKey<16>, RID, GenericComparator<16>>;

template class IndexIterator<GenericKey<32>, RID, GenericComparator<32>>;

template class IndexIterator<GenericKey<64>, RID, GenericComparator<64>>;

}  // namespace bustub
